<script setup lang="ts">
import LayoutTitle from '@/components/LayoutTitle/index.vue'
import Content from '@/components/Content/index.vue'
import ContentTitle from '@/components/ContentTitle/index.vue'
import { useAuth, useSocket } from '@/stores/index'
import APIWallet from '@/api/wallet'
import type { PayQrcodeData } from '@/api/wallet/types'
import { ElMessageBox, ElMessage } from 'element-plus'

const { info } = storeToRefs(useAuth())

const $router = useRouter()

const { socket } = storeToRefs(useSocket())

function onMessage(e: any) {
    const data = JSON.parse(e.data)
    const type = data.type
    switch (type) {
        case 'recharge':
            ElMessageBox.confirm(
                '充值成功',
                '提示', {
                confirmButtonText: '查看订单',
                cancelButtonText: '取消',
                type: 'success',
            }).then(() => {
                $router.push({
                    name: 'Wallet'
                })
            }).catch(() => {
                reset()
                moneyInput.value = ''

            })
            break
    }
}

watch(socket, (newValue) => {
    if (newValue) {
        socket?.value?.addEventListener('message', onMessage)
    }
}, { immediate: true })

onBeforeUnmount(() => {
    socket?.value?.removeEventListener('message', onMessage)
})

const money = shallowRef<string>('0')

const moneyInput = shallowRef<string>('')

function handleInput(value: any) {
    moneyInput.value = value.target.value.replace(/[^\d]/g, '')
}

const topupWay = shallowRef<string>('alipay')

function handleVerifyMoney() {
    if (!moneyInput.value) return
    if (moneyInput.value == '0') return ElMessage.error('请输入大于0的金额')
    money.value = moneyInput.value
}

const qrCode = shallowRef<string>('')

const loading = shallowRef<boolean>(false)

const financeRechargeList = ref<any>([])

watch([topupWay, money, info, financeRechargeList], (newValue) => {
    if (newValue[1] != '0' && newValue[2].id && newValue[3].length != 0) {

        const giftAmountList = financeRechargeList.value.filter((item: any) => item.discount_amount == money.value)
        let giftAmount = 0
        if (giftAmountList.length != 0) {
            giftAmount = giftAmountList[0].amount
        } else {
            giftAmount = Number(newValue[1])
        }

        const data: PayQrcodeData = {
            pay_type: newValue[0],
            amount: Number(newValue[1]),
            recharge_type: newValue[3][0].recharge_type,
            gift_amount: giftAmount
        }
        loading.value = true
        APIWallet.payQrcode(data).then(({ data }) => {
            qrCode.value = data.qr_code
        }).finally(() => {
            loading.value = false
        })
    }
})


function getFinanceRecharge() {
    APIWallet.getFinanceRecharge().then(({ data }) => {
        financeRechargeList.value = data
    })
} getFinanceRecharge()

watch(financeRechargeList, (newValue) => {
    if (newValue.length != 0) {
        money.value = newValue[0].discount_amount
    }
}, { deep: true })

function reset() {
    if (financeRechargeList.value.length != 0) {
        money.value = financeRechargeList.value[0].discount_amount
    }
}

</script>

<template>
    <div class="topup">
        <LayoutTitle class="nav" title="充值中心" />
        <Content class="content">
            <ContentTitle title="账号基本信息：" />
            <div class="info">
                <div class="con">
                    <div class="label">用户名：</div>
                    <div class="value">{{ info.username }}</div>
                </div>
                <div class="con">
                    <div class="label">账号ID：</div>
                    <div class="value">{{ info.Invite_code }}</div>
                </div>
            </div>
        </Content>
        <Content class="content">
            <ContentTitle title="充值金额："
                content="1、首次金额有折扣，例如充值3000，只需要付折扣后的费用即可(自定义金额不打折扣);<br />2、首次可以选择任意金额进行充值，充值第一笔后，充值页面自动消失，不再享受充值折扣;<br />3、请理性充值;" />
            <div class="select-money">
                <div class="select-money-item " @click="money = item.discount_amount"
                    v-for="item in financeRechargeList" :key="item.id"
                    :class="{ 'select-money-item-active': money == item.discount_amount }">
                    {{ item.title }}
                    <div class="frist-recharge-user" v-if="item.recharge_type == 'frist_recharge_user'">首充</div>
                </div>
            </div>
            <div class="search-input">
                <input type="text" placeholder="输入自定义金额" v-model="moneyInput" @input="handleInput">
                <button type="button" @click="handleVerifyMoney">确定</button>
            </div>
        </Content>
        <Content class="content">
            <ContentTitle title="充值方式：" />
            <div class="topup-way">
                <el-radio-group v-model="topupWay">
                    <el-radio value="alipay">支付宝</el-radio>
                    <el-radio value="wechatpay">微信</el-radio>
                    <el-radio value="3" disabled>银行转账</el-radio>
                    <el-radio value="4" disabled>利润划账</el-radio>
                </el-radio-group>
            </div>
            <div class="give-money">
                <div class="code" v-loading="loading">
                    <img v-if="qrCode" :src="qrCode" alt="qrCode">
                </div>
                <div class="text">
                    <p>充值金额：<span>{{ money }}元</span></p>
                    <p>请用<span v-if="topupWay == 'alipay'">支付宝</span><span
                            v-if="topupWay == 'wechatpay'">微信</span>进行扫描充值！</p>
                </div>
            </div>
        </Content>
    </div>
</template>

<style lang="scss" scoped>
.topup {
    .nav {
        margin-bottom: 32px;
    }

    .content {
        width: 75%;
        margin: 0 auto;
        margin-bottom: 30px;

        .give-money {
            display: flex;
            gap: 0 70px;
            padding: 0 50px;
            margin-top: 30px;

            .text {
                display: flex;
                flex-direction: column;
                gap: 20px 0;
                justify-content: flex-end;
                color: rgba(16, 16, 16, 1);
                font-size: 14px;

                p {
                    span {
                        color: #F91414;
                    }
                }
            }

            .code {
                width: 120px;
                height: 120px;
                background-color: #eeeeee;

                img {
                    width: 100%;
                    height: 100%;
                    display: block;
                }
            }
        }

        .topup-way {
            padding: 0 50px;
            margin-top: 30px;
        }

        .search-input {
            display: flex;
            margin-left: 50px;
            margin-top: 50px;

            input {
                text-indent: 20px;
                box-sizing: border-box;
                display: block;
                width: 440px;
                height: 50px;
                line-height: 20px;
                border-radius: 5px 0 0 5px;
                font-size: 14px;
                border: 1px solid rgba(56, 148, 255, 1);
                outline: none;
            }

            button {
                box-sizing: border-box;
                display: block;
                width: 100px;
                height: 50px;
                border-radius: 0px 5px 5px 0px;
                background-color: rgba(56, 148, 255, 1);
                color: #ffffff;
                font-size: 14px;
                border: 1px solid rgba(56, 148, 255, 1);
                cursor: pointer;
            }
        }

        .select-money {
            display: grid;
            grid-template-columns: repeat(6, 1fr);
            padding: 0 50px;
            margin-top: 30px;
            gap: 30px 0;

            div.select-money-item-active {
                background-color: rgba(56, 148, 255, 1);
                color: #ffffff;
            }

            .select-money-item {
                width: 100px;
                height: 50px;
                line-height: 50px;
                border-radius: 5px;
                font-size: 14px;
                text-align: center;
                color: #888888;
                background-color: rgba(238, 238, 239, 1);
                cursor: pointer;
                position: relative;

                .frist-recharge-user {
                    position: absolute;
                    right: -10px;
                    top: -10px;
                    background-color: #f89898;
                    font-size: 12px;
                    width: 30px;
                    height: 20px;
                    line-height: 20px;
                    border-radius: 5px;
                    color: #ffffff;
                }
            }
        }

        .info {
            display: flex;
            margin: 30px 0;
            padding: 0 50px;

            .con {
                display: flex;
                align-items: center;
                flex: 1;

                .value {
                    color: rgba(154, 154, 154, 1);
                    font-size: 14px;
                }

                .label {
                    color: rgba(16, 16, 16, 1);
                    font-size: 15px;
                }
            }
        }
    }
}
</style>
